package org.dbutils.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.dbutils.dao.StaffDao;
import org.dbutils.entity.Staffs;
import org.dbutils.util.DruidUtil;

import java.sql.SQLException;
import java.util.List;

/**
 * @author ZJL
 * Staffs 接口的实现 - 基于 Apache DbUtils 的实现
 * @date 2025-02-25
 */
public class StaffDaoImplDbUtils implements StaffDao {
    // 定义DBUtils 工具类的 SQL 执行器
    QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());

    @Override
    public int addStaff(Staffs staff) {
        // 第一：定义要操作的SQL语句
        String sql = "insert into staffs(name,age,phone,sta_pos) values (?,?,?,?);";
        // 第二： 执行 SQL 语句
        Object[] params = {
                staff.getName(), staff.getAge(), staff.getPhone(), staff.getStaPos()
        };
        try {
            return qr.update(sql, params);
        } catch (SQLException e) {
            throw new RuntimeException("添加失败！", e);
        }
    }

    @Override
    public int updateStaff(Staffs staff) {
        String sql = "update staffs set name = ?,age = ?,phone = ?,sta_pos = ?,update_time = ? where id = ?;";
        Object[] params = {
                staff.getName(), staff.getAge(), staff.getPhone(),
                staff.getStaPos(), staff.getUpdateTime(), staff.getId()
        };
        try {
            return qr.update(sql, params);
        } catch (SQLException e) {
            throw new RuntimeException("修改失败！",e);
        }
    }

    @Override
    public int deleteStaff(int id) {
        String sql = "delete from staffs where id=?";
        try {
            return qr.update(sql, id);
        } catch (SQLException e) {
            throw new RuntimeException("删除失败！",e);
        }
    }

    @Override
    public List<Staffs> staffsList(int currenPage, int pageSize) {
        String sql = "select id,name,age,phone,sta_pos as staPos,add_time as addTime,update_time as updateTime from staffs limit ?,?;";
        int limit = (currenPage - 1) * pageSize;
        Object[] params = {limit, pageSize};
        try {
            return qr.query(sql, new BeanListHandler<>(Staffs.class), params);
        } catch (SQLException e) {
            throw new RuntimeException("分页查询异常",e);
        }
    }

    @Override
    public Staffs selectStaffById(int id) {
        String sql = "select id,name,age,phone,sta_pos as staPos,add_time as addTime,update_time as updateTime from staffs where id=?";
        try {
            return qr.query(sql, new BeanHandler<>(Staffs.class), id);
        } catch (SQLException e) {
            throw new RuntimeException("根据id查询异常！",e);
        }
    }
}
